package com.openthinks.joyniproject.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.openthinks.joyniproject.DataLoader;
import com.openthinks.joyniproject.model.Dept;
import com.openthinks.joyniproject.model.Role;
import com.openthinks.joyniproject.model.UserInfo;
import com.openthinks.joyniproject.service.AccountService;
import com.openthinks.joyniproject.service.DeptService;
import com.openthinks.joyniproject.utils.BaseUtil;

/**
 * 
 * @since 
 *		v1.0
 * @version
 * 		v1.0, 2013-06-28 21:16:35
 * @author 
 *		Cloud
 */
@Controller
@RequestMapping("/userTree")
public class UserTreeController {

	@Autowired
	private DeptService deptService;
	
	@Autowired
	private AccountService accountService;
	
	/**
	 * 获取部门及人员
	 */
	@RequestMapping(value="/find",method=RequestMethod.GET)
    @ResponseBody
	public List<Map<String, String>> findSubByPid(@RequestParam Map<String,String> data, HttpServletRequest request) {
		
		Long pid = BaseUtil.parseLong(data.get("pid"));
		pid = pid == null ? Dept.ROOT_ID : pid;
		
		//加载部门
		List<Dept> list = deptService.findSubByPid(pid);
		List<Map<String, String>> ret = new ArrayList<Map<String,String>>();
		for (Dept bean : list) {
			Map<String, String> map = new HashMap<String, String>();
			String deptId = bean.getId().toString();
			map.put("id", deptId);
			map.put("name", bean.getName());
			map.put("isParent", "true");
			map.put("nocheck", "true");
			ret.add(map);
		}
		
		//加载部门下的人员
		List<UserInfo> userList = accountService.getUserInfoByDeptId(pid + "");
		for (UserInfo user : userList) {
			Long rid = BaseUtil.parseLong(user.getRoleId());
			String rname = "";
			if (rid != null) {
				Role role = DataLoader.getRoleData().get(rid);
				if (role != null) {
					rname = "(" + role.getName() + ")";
				}
			}
			
			Map<String, String> map = new HashMap<String, String>();
			map.put("id", user.getId());
			map.put("name", user.getName() + rname);
			map.put("isParent", "false");
			map.put("nocheck", "false");
			ret.add(map);
		}
		return ret;
	}
}
